﻿#include "JsonUtil.h"
#include <stdlib.h>

std::string& JsonUtil::ReplaceAll(std::string& str, const std::string& old_value, const std::string& new_value)
{
	while (true)
	{
		std::string::size_type pos(0);
		if ((pos = str.find(old_value)) != std::string::npos)
			str.replace(pos, old_value.length(), new_value);
		else
			break;
	}
	return   str;
}

std::string JsonUtil::ReplaceUTF8(std::string body)
{
	// 替换libcurl生成的转义字符
	std::string strUtf8 = body;
	strUtf8 = ReplaceAll(strUtf8, "\\n\\t", "");
	strUtf8 = ReplaceAll(strUtf8, "\\n", "");
	strUtf8 = ReplaceAll(strUtf8, "\\\"", "\"");
	strUtf8 = ReplaceAll(strUtf8, "\"[\"", "[");
	strUtf8 = ReplaceAll(strUtf8, "\"]\"", "]");
	strUtf8 = ReplaceAll(strUtf8, "\"[", "[");
	strUtf8 = ReplaceAll(strUtf8, "]\"", "]");
	strUtf8 = ReplaceAll(strUtf8, "\"{", "{");
	strUtf8 = ReplaceAll(strUtf8, "}\"", "}");
	strUtf8 = ReplaceAll(strUtf8, "\\n", "");
	return strUtf8;
}

bool JsonUtil::Parse(std::string body)
{
	try
	{
		std::stringstream iss;
		iss.str(ReplaceUTF8(body));

		boost::property_tree::ptree result;
		boost::property_tree::json_parser::read_json(iss, m_root);
		return true;
	}
	catch (boost::property_tree::ptree_error& e)
	{
		printf("%s\n", e.what());
	}
	return false;
}

std::string JsonUtil::GetString(std::string path, std::string v)
{
	std::string value = v;
	boost::optional<std::string> node = m_root.get_optional<std::string>(path);
	if (node)
	{
		value = m_root.get<std::string>(path, v);
	}
	return value;
}

int JsonUtil::GetInt(std::string path, int v)
{
	int value = v;
	boost::optional<int> test = m_root.get_optional<int>(path);
	if (test)
	{
		value = m_root.get<int>(path, v);
	}
	return value;
}

float JsonUtil::GetFloat(std::string path, float v)
{
	float value = v;
	boost::optional<float> test = m_root.get_optional<float>(path);
	if (test)
	{
		value = m_root.get<float>(path, v);
	}
	return value;
}

bool JsonUtil::GetBoolean(std::string path, bool v)
{
	bool value = v;
	boost::optional<bool> test = m_root.get_optional<bool>(path);
	if (test)
	{
		value = m_root.get<bool>(path, v);
	}
	return value;
}

bool JsonUtil::HasNode(std::string path)
{
	boost::optional<boost::property_tree::ptree&> node = m_root.get_child_optional(path);
	if (node)
	{
		return true;
	}
	return false;
}